package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author BaiZY on 2020/9/2.
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    public static final String KEY_PREFIX = "sms_code:";

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Boolean exists(String data, Integer type) {
        if (type != 1 && type != 2 || StringUtils.isEmpty(data)){
            throw new LyException(400,"请求参数有误");
        }

        return query().eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {

        User user = this.getOne(new QueryWrapper<User>().eq("username", username));

        if (user == null){
            throw new LyException(400,"用户名不存在");
        }
        String pwd = user.getPassword();

        if (!passwordEncoder.matches(password,pwd)){
            throw new  LyException(400,"用户名或密码错误");
        }

        return new UserDTO(user);
    }

    @Override
    public void sendCode(String phone) {

        //判断是否是手机号
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"手机号格式有误");
        }
        //生成验证码
        String code = RandomStringUtils.randomNumeric(6);

        //存入redis中
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code,3, TimeUnit.MINUTES);

        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        //消息队列转发消息
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
    }

    @Transactional
    @Override
    public void register(User user, String code) {

        //从redis中取出验证码进行验证
        String codeCache = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (StringUtils.isEmpty(codeCache) || !StringUtils.equals(code,codeCache)){
            throw new LyException(400,"验证码校验失败");
        }
        String pwd = passwordEncoder.encode(user.getPassword());
        user.setPassword(pwd);

        //存入数据库
        save(user);
    }
}
